<template>
  <Dialog
    v-model="dialogVisible"
    width="600px"
    title="新增"
    :before-close="() => closeDialog(formRef)"
    :close-on-click-modal="true"
  >
    <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
      <el-form-item label="位置" prop="position">
        <el-select v-model="form.position" placeholder="请选择位置">
          <el-option
            v-for="item in positionOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="矿机" prop="pm_ids">
        <div class="w-full flex items-center">
          <el-select-v2
            v-model="form.pm_ids"
            :options="salesPidsOptions"
            :placeholder="'请选择矿机'"
            clearable
            multiple
            filterable
            :props="{ label: 'productname', value: 'id' }"
            @change="handleSalesPidsChange"
          />
          <el-button
            type="primary"
            @click="handleOpenDialog"
            class="ml-2"
            :disabled="!form.position"
            >选择</el-button
          >
        </div>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="1" placeholder="请输入排序" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)">取消</el-button>
      <el-button type="primary" @click="submit(formRef)">确定</el-button>
    </template>

    <!-- 矿机选择弹窗 -->
    <recommend-dialog
      ref="recommendDialogRef"
      v-model="recommendDialogVisible"
      :position="form.position"
      @expose-multiple-data="getExposeSalesPidsData"
      @close="handleCloseRecommendDialog"
    />
  </Dialog>
</template>

<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { type FormInstance, type FormRules, ElMessage } from 'element-plus'
import { addApi, getEnumApi } from '@/api/recommendProduct'
import RecommendDialog from './components/recommendDialog/index.vue'

// 定义组件名称
defineOptions({
  name: 'Add'
})

const emit = defineEmits(['refresh'])

const dialogVisible = ref<boolean>(false)
const recommendDialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance>()
const recommendDialogRef = ref()

const positionOptions = ref<any[]>([])

const form = ref<Record<string, any>>({
  pm_ids: [],
  pm_names: [],
  position: undefined,
  sort: 1
})

// 表单验证规则
const rules = ref<FormRules>({
  pm_ids: [
    {
      required: true,
      message: '请选择矿机',
      trigger: ['blur']
    }
  ],
  position: [
    {
      required: true,
      message: '请选择位置',
      trigger: ['blur']
    }
  ],
  sort: [
    {
      required: true,
      message: '请输入排序',
      trigger: ['blur']
    }
  ]
})

const salesPidsOptions = ref<any[]>([])

const handleSalesPidsChange = (val: number[]) => {
  form.value.pm_ids = val
  form.value.pm_names = val.map((id) => {
    const selected = salesPidsOptions.value.find((item) => item.id === id)
    return selected ? selected.productname : ''
  })
}

// 打开矿机选择弹窗
const handleOpenDialog = () => {
  recommendDialogVisible.value = true
  nextTick(() => {
    if (!recommendDialogRef.value) return
    recommendDialogRef.value.initialize(form.value.pm_ids ? [{ id: form.value.pm_ids[0] }] : [])
  })
}

// 关闭矿机选择弹窗
const handleCloseRecommendDialog = () => {
  recommendDialogVisible.value = false
}

// 选择矿机回调
const getExposeSalesPidsData = (val: any[]) => {
  console.log(val, 78)
  if (!val || !val.length) return
  salesPidsOptions.value = val
  nextTick(() => {
    form.value.pm_ids = val.map((item: any) => item.id)
  })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const params = {
          pm_id: form.value.pm_ids.join(','), // 将数组转换为逗号分隔的字符串
          position: form.value.position,
          sort: form.value.sort
        }
        const res = await addApi(params)
        if (res.code === 0) {
          ElMessage.success('新增成功')
          closeDialog(formEl)
          emit('refresh')
        } else {
          ElMessage.error('新增失败')
        }
      } catch (error) {
        console.error('提交失败', error)
        ElMessage.error('新增失败')
      }
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {
    pm_ids: [],
    pm_names: [],
    position: undefined,
    sort: 1
  }
  salesPidsOptions.value = [] // 清空选项数据
  formEl.resetFields()
  dialogVisible.value = false
}

const getBackShow = () => {
  dialogVisible.value = true
}

// 获取枚举数据
const getEnumData = async () => {
  try {
    const res = await getEnumApi()
    if (res.code === 0) {
      positionOptions.value = res.data.position || []
    }
  } catch (error) {
    console.error('获取枚举数据失败', error)
  }
}

// 在组件挂载时获取枚举数据
onMounted(() => {
  getEnumData()
})

// 导出组件
defineExpose({
  dialogVisible,
  getBackShow
})
</script>

<style lang="less" scoped>
.m-r-4 {
  margin-right: 16px;
}

.ml-2 {
  margin-left: 8px;
}
</style>
